import Vue from 'vue'
import VueRouter from 'vue-router'

const Login = () => import("../components/Login.vue")
const Home = () => import("../components/Home.vue")
const Welcome = () => import("../components/Welcome.vue")
const Users = () => import("../components/user/Users.vue")
const Rights = () => import("../components/power/Rights.vue")
const Roles = () => import("../components/power/Roles.vue")
const Categories = () => import("../components/goods/Categories.vue")
const Parmas = () => import("../components/goods/Parmas.vue")
const List = () => import("../components/goods/List.vue")
const Add = () => import("../components/goods/Add.vue")
const Order = () => import("../components/order/Order.vue")
const Report = () => import("../components/report/Report.vue")

Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/login'
  }, {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/home/welcome',
    children: [{
      path: '/home/welcome',
      component: Welcome
    }, {
      path: '/home/users',
      component: Users
    }, {
      path: '/home/rights',
      component: Rights
    }, {
      path: '/home/roles',
      component: Roles
    }, {
      path: '/home/categories',
      component: Categories
    }, {
      path: '/home/params',
      component: Parmas
    }, {
      path: '/home/goods',
      component: List
    }, {
      path: '/home/goods/add',
      component: Add
    }, {
      path: '/home/orders',
      component: Order
    }, {
      path: '/home/reports',
      component: Report
    }]
  }
]

const router = new VueRouter({
  mode: 'hash',
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径而来
  // next 是一个函数，表示放行
  // next()放行    next('/login')强制跳转
  if (to.path === '/login') {
    return next()
  } else {
    // 验证是否有token
    const tokenStr = window.sessionStorage.getItem('token')
    if (!tokenStr) {
      // 没有的话就强制跳转到login页面
      return next('/login')
    } else {
      // 有的话就直接放行
      next()
    }
  }

})

export default router